package geekTime.chapter6WaitNotify;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LinGer on 2019/6/26
 */
public class Allocator {

    private List<Object> als = new ArrayList<>();

    /**
     * 防止死锁，一次性申请所有资源
     */
    public synchronized void apply(Object from, Object to){
        //使用while而不是if。经典写法，避免“条件曾经满足过”这个问题
        while (!als.contains(from) || !als.contains(to)) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        als.add(from);
        als.add(to);
    }

    /**
     * 归还资源
     */
    public synchronized void free(Object from, Object to){
        als.remove(from);
        als.remove(to);
        notifyAll();
    }


}
